package org.zxyj.manage.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.zxyj.core.constants.Dict;
import org.zxyj.core.constants.Keys;
import org.zxyj.core.constants.SysParamsDict;
import org.zxyj.core.entity.Pagination;
import org.zxyj.core.entity.Result;
import org.zxyj.core.exception.ServiceException;
import org.zxyj.core.utils.Common;
import org.zxyj.core.utils.FileUtil;
import org.zxyj.core.utils.MessageUtil;
import org.zxyj.core.utils.RequestUtils;
import org.zxyj.core.utils.UUIDUtils;
import org.zxyj.manage.entity.CoursePaper;
import org.zxyj.manage.entity.CoursePaperCrop;
import org.zxyj.manage.entity.CoursePaperDetail;
import org.zxyj.manage.entity.CourseTemplate;
import org.zxyj.manage.entity.CourseTemplateArea;
import org.zxyj.manage.service.ICourseTemplateService;
import org.zxyj.manage.service.ICropService;
import org.zxyj.manage.service.ICheckService;
import org.zxyj.manage.service.ICoursePaperService;

/**
 * 科目答卷校验控制类
    * @ClassName: ExamPaperManageController
    * @author liuyong
    * @date 2016年8月8日
 */
@Controller
@RequestMapping("/manage/examPaper")
public class ExamPaperManageController extends BatchController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	//读取配置文件
    //private static PropertiesUtil configProp = PropertiesUtil.newInstance(Thread.currentThread().getContextClassLoader().getResource("").getPath() + "config/config.properties");
    
    @Autowired
    private ICoursePaperService coursePaperService;
    @Autowired
	private ICourseTemplateService courseTemplateService;
	@Autowired
	private ICropService cropService;
	@Autowired
	private ICheckService checkService;
	
	@RequestMapping({"","/","/index"})
	public ModelAndView index(ModelAndView mv) {
		mv.setViewName(Views.LIST_VIEW);
		Map<String, Object> criteria = new HashMap<String, Object>();
		Object query_batch = getParaValue("query_batch");
		Object query_grade = getParaValue("query_grade");
		Object query_course = getParaValue("query_course");
		criteria.put("batchId", query_batch);
		criteria.put("gradeNo", query_grade);
		criteria.put("courseNo", query_course);
		criteria.put("userId", Common.findUserSessionId());
		Pagination page = (Pagination) getRequestAttr("pagination");
		Pagination pagination = courseTemplateService.getListEntities(criteria, page);
		mv.addObject(Keys.KEY_PAGINATION, pagination);
		List<Map<String,Object>> batchs = courseTemplateService.getExamBatchs(criteria);
		mv.addObject("batchs", batchs);
		mv.addObject("query_batch", query_batch);
		mv.addObject("query_grade", query_grade);
		mv.addObject("query_course", query_course);
		return mv;
	}
	
	/**
	 * 调转到上传附件页面
	    * @Title: uploadExamPaperUI
	    * @param @param mv
	    * @param @return    参数
	    * @return ModelAndView    返回类型
	    * @throws
	 */
	@RequestMapping("/upload/uploadExamPaperUI")
    public ModelAndView uploadExamPaperUI(ModelAndView mv){
		mv.setViewName(Views.UPLOAD_VIEW);
        mv.addObject("batchId", getParaValue("batchId"));
        mv.addObject("gradeNo", getParaValue("gradeNo"));
        mv.addObject("courseNo", getParaValue("courseNo"));
        return mv;
    }
	
	/**
	 * 科目答卷压缩包上传
	    * @Title: uploadPaperZip
	    * @param @param request
	    * @param @param files
	    * @param @return
	    * @param @throws IOException    参数
	    * @return Map<String,Object>    返回类型
	    * @throws
	 */
	@ResponseBody
	@RequestMapping("/uploadPaperZip/exec")
	public Map<String,Object> doUploadPaperZip(HttpServletRequest request, @RequestParam("files[]") MultipartFile[] files) throws IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		String dotChar = ".";
		String resultCode = SysParamsDict.STATUS_CODE.SUCCESS.getValue();
		String sessionId = getParaValue("jsessionid");
		request.getSession().setAttribute("jsessionid",sessionId);
		//获取参数
		String batchId = getParaValue("batchId")==null?"":getParaValue("batchId");
        String gradeNo = getParaValue("gradeNo")==null?"":getParaValue("gradeNo");
        String courseNo = getParaValue("courseNo")==null?"":getParaValue("courseNo");
		
        //处理附件上传
		String fileDir = MessageUtil.getExtConfig("fj.course.paper.url");//文件存放目录
		String relativePath = "zip/"+batchId+"/";
		String filePath = fileDir + relativePath; //真实目录名  
		//创建目录
		FileUtil.createDir(filePath);
        
        try{
	        for (MultipartFile f : files) {
	        	if (f != null && !f.isEmpty()) {
	        		long fileSize = f.getSize();
	        		String fileName = f.getOriginalFilename();
	        		String fileType = fileName.substring(fileName.lastIndexOf(dotChar)+1).toLowerCase();//检查文件后缀格式  
	        		String folderName = ""+System.currentTimeMillis();//创建文件唯一名称  
	        		StringBuffer sbRealPath = new StringBuffer();  
	                sbRealPath.append(filePath).append(folderName).append(dotChar).append(fileType); //真实上传路径 
	                String relativePath_zip = relativePath + folderName + "." +fileType;//相对路径
	                File file = new File(sbRealPath.toString());//写入文件 
	        		FileUtils.copyInputStreamToFile(f.getInputStream(), file);
	        		
	        		try{
		        		//保存Zip附件记录
	                    String id = UUIDUtils.UUID();
	                    CoursePaper entity = new CoursePaper();
	                    entity.setId(id);
	                    entity.setBatchId(batchId);
	                    entity.setCourseNo(courseNo);
	                    entity.setGradeNo(gradeNo);
	                    entity.setFolderName(folderName);
	                    entity.setFileSize(fileSize+"");
	                    entity.setFilePath(relativePath_zip);
	                    entity.setFileName(fileName);
	                    entity.setFileType(fileType);
	                    this.coursePaperService.insertCoursePaper(entity);
	                    
	                    //解压Zip
	                    Map<String,Object> params = new HashMap<String,Object>();
	                    params.put("batchId", batchId);
                        params.put("gradeNo", gradeNo);
                        params.put("courseNo", courseNo);
                        params.put("mbMap", this.courseTemplateService.getTemplateList(params));
	                    params.put("id", id);
	                    params.put("fileDir", fileDir);
	                    int index = sbRealPath.lastIndexOf("/");
                        String strUrl = sbRealPath.substring(0,index+1);
                        String outPath = strUrl+folderName+"/";//解压后文件输出路径
                        relativePath = relativePath + folderName+"/";
                        String fileOutPath = FileUtil.unZip(id,sbRealPath.toString(),outPath);//解压路径下Zip包
                        params.put("fileOutPath", fileOutPath);
                        params.put("relativePath", relativePath);
                        if(StringUtils.isNotEmpty(fileOutPath)){
                            //解压文件后扫描文件，将文件信息保存到数据表中
                            this.coursePaperService.getPaperFile(params);
                            logger.info("save uploadPaperZip data is success!!! exec method is uploadPaperZip.");
                        }else{
                        	this.coursePaperService.deleteCoursePaper(params);
                        	resultCode = SysParamsDict.STATUS_CODE.FAIL.getValue();
                        	logger.error("deleteCoursePaper data is fail!!! exec method is uploadPaperZip.");
                        }
                        
                        //删除Zip附件
                        /*if(file.delete()){
                        	this.coursePaperService.deleteCoursePaper(params);
                        }*/
	        		}catch(Exception ex){
	        			resultCode = SysParamsDict.STATUS_CODE.FAIL.getValue();
	        			logger.error("save uploadPaperZip data is fail!!! exec method is uploadPaperZip.", ex);
	        		}
	        	}
	        }
        }catch(Exception ex){
        	resultCode = SysParamsDict.STATUS_CODE.FAIL.getValue();
        	logger.error("save uploadPaperZip data is fail!!! exec method is uploadPaperZip.", ex);
        }
        map.put("resultCode", resultCode);
        return map;
	}
	
	/**
     * 查询科目答卷模板是否存在
     * @throws IOException
     * @see   [类、类#方法、类#成员]
     * @since [产品/模块版本]
     */
    @ResponseBody
    @RequestMapping("/check/checkTemplateExists")
    public void checkTemplateExists(@RequestBody Map<String, Object> criteria,HttpServletRequest request) throws IOException{
    	//Result<?> result = new Result<String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();

    	//清空校验session
    	removeSessionAttr("djzs");
    	removeSessionAttr("kmdjJyjgMap");
    	removeSessionAttr("kmdjQkMap");
    	removeSessionAttr("sbsbMap");
    	removeSessionAttr("sbcgMap");
    	removeSessionAttr("qkksMap");
    	removeSessionAttr("bdsbMap");
        //裁剪用session数据
        removeSessionAttr("kscjMapSession1");
        removeSessionAttr("kscjMapSession2");
        removeSessionAttr("cropSqlMapSession");
        removeSessionAttr("cropUpdateSqlMapSession");
        setSessionAttr("kscjMapSession1", new ConcurrentHashMap<String,Map<String,String>>());//存放考生裁剪参数-正面
        setSessionAttr("kscjMapSession2", new ConcurrentHashMap<String,Map<String,String>>());//存放考生裁剪参数-反面
        setSessionAttr("cropSqlMapSession", new ConcurrentHashMap<String,Object>());//考生裁剪图片
        setSessionAttr("cropUpdateSqlMapSession", new ConcurrentHashMap<String,Object>());//考生裁剪update图片
        
        //查询科目模板
        List<CourseTemplate> list = this.courseTemplateService.listEntities(criteria);
        //String resultCode = "";//状态值：0-模板没查到，1-操作成功，2-模板没查到,3-考生未查到,4-正面答卷未查到 9-成功
        if(!CollectionUtils.isEmpty(list)){
        	List<String> tempIds = new ArrayList<String>();
            //科目模板会有2份，区分正反面 
        	CourseTemplate temp = list.get(0);
            String courseTemplateId1 = temp.getId();//模板id
            resultMap.put("courseTemplateId1",courseTemplateId1);
            tempIds.add(courseTemplateId1);
            
            //判断是否存在反面模板
            String courseTemplateId2="";
            if(list.size()>1){
            	courseTemplateId2 = list.get(1).getId();//模板id
            	resultMap.put("courseTemplateId2",courseTemplateId2);
            	tempIds.add(courseTemplateId2);
            }

            //查询答卷信息列表并进行校验
            criteria.put("courseTemplateId1",courseTemplateId1);
            criteria.put("courseTemplateId2",courseTemplateId2);
            criteria.put("tempIds",tempIds);
            criteria.put("session",request.getSession());
            this.checkService.checkTemplate(criteria);
            //ConcurrentHashMap<String,Object> map = RequestUtils.getCurrSessionAttrMap("kmdjJyjgMap");
            //resultCode = (String) map.get("resultCode");
            resultMap.putAll(RequestUtils.getCurrSessionAttrMap("kmdjJyjgMap"));
        }else{
        	//resultCode = SysParamsDict.CHECK_STATUS_CODE.NOTEMP.getValue();
        }
        
        //result.setData(resultMap);
        //result.setResultCode(resultCode);
        //return result;
    }
    
    /**
     * 查询科目答卷校验失败的信息
     * @see   [类、类#方法、类#成员]
     * @since [产品/模块版本]
     */
    @ResponseBody
    @RequestMapping("/check/checkFailPaperExists")
    public Result<?> checkFailPaperExists(@RequestBody Map<String, Object> criteria){
    	Result<?> result = new Result<String>();
    	String resultCode = SysParamsDict.STATUS_CODE.FAIL.getValue();
        
        //查询正面模板设置数据
    	criteria.put("zfmType", 1);
  		criteria.put("existsCondition", true);
  		String[] lxArr = {"1","9"};
      	criteria.put("lxList", Arrays.asList(lxArr));
      	Map<String,CourseTemplateArea> mbMap = this.courseTemplateService.getTemplateAreaMap(criteria);
  		if(!mbMap.containsKey("kh")){
  			result.setResultCode(SysParamsDict.CHECK_STATUS_CODE.NO_KSBH.getValue());
  	        return result;
  		}
  		if(!mbMap.containsKey("qk")){
  			result.setResultCode(SysParamsDict.CHECK_STATUS_CODE.NO_QK.getValue());
  	        return result;
  		}
  		
  		//查询校验失败答卷
  		criteria.put("isPass", 2);
        List<CoursePaperDetail> list = this.coursePaperService.findCoursePaperDetailList(criteria);
        if(!CollectionUtils.isEmpty(list)){
        	resultCode = SysParamsDict.CHECK_STATUS_CODE.SUCCESS.getValue();
        }
        result.setResultCode(resultCode);
        return result;
    }
    
    /**
     * 获取校验进度session参数
        * @Title: getPaperCheckSession
        * @param @param request
        * @param @return    参数
        * @return Result<?>    返回类型
        * @throws
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping("/check/getPaperCheckSession")
    public Result<?> getPaperCheckSession(@RequestBody Map<String, Object> criteria){
    	Result<?> result = new Result<String>();
    	Map<String,Object> resultMap = new HashMap<String,Object>();
    	ConcurrentHashMap<String,String> map = (ConcurrentHashMap<String, String>) getSessionAttr("kmdjJyjgMap");
    	String resultCode = map.get("resultCode");
    	int djzs = map==null?0:map.get("djzs")==null?0:Integer.parseInt(map.get("djzs"));
    	if (djzs < 1) {
    		resultMap.put("djzs",0);
    		resultMap.put("clzs",0);
    		resultMap.put("bl",0);
    	}else{
    		if(!SysParamsDict.CHECK_STATUS_CODE.NOTEMP.getValue().equals(resultCode)) {
            	int clzs = 0,succCount=0,sbsbCount=0,bdsb=0,qkCount=0;
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    String key =  entry.getKey();
                    String val =  entry.getValue();
                    if (StringUtils.isNotEmpty(key)){
                        if (key.startsWith("clzs_")) {
                            clzs += Integer.valueOf(val).intValue();
                        }else if (key.startsWith("succCount_")) {
                            succCount += Integer.valueOf(val).intValue();
                        }else if (key.startsWith("sbsbCount_")) {
                            sbsbCount += Integer.valueOf(val).intValue();
                        }else if (key.startsWith("bdsbCount_")) {
                            bdsb += Integer.valueOf(val).intValue();
                        }else if (key.startsWith("qkCount_")) {
                            qkCount += Integer.valueOf(val).intValue();
                        }
                    }
                }
                
                if((succCount+sbsbCount)>clzs){
                    //将成功数除2
                    succCount = succCount/2;
                    //将失败数除2
                    sbsbCount = sbsbCount/2;
                }
                if(clzs>=djzs){
                    resultCode = SysParamsDict.CHECK_STATUS_CODE.PASS.getValue();
                    map.put("resultCode", resultCode);
                    
                    //调用图片裁剪保存方法保存最终数据
                    //saveCropData();
                }
                //判断线程出异常的情况处理数量小于最大数据量
                int bl =0;
                if(djzs>0){
                    bl = (int)((clzs / Double.parseDouble(djzs+"")) * 100);
                }
                resultMap.put("djzs",djzs);
                resultMap.put("clzs",clzs);
                resultMap.put("bl",bl);
                resultMap.put("allCount", djzs);//总记录数
                resultMap.put("succCount", succCount);//成功记录数
                resultMap.put("sbsbCount", sbsbCount);//识别失败记录数
                resultMap.put("bdsb", bdsb);//比对失败记录数
                resultMap.put("qkCount", qkCount);//缺考记录数
            }
        }
    	result.setData(resultMap);
		result.setResultCode(resultCode);
    	return result;
    }
    
    /**
     * 清空上传答卷信息
     * @see   [类、类#方法、类#成员]
     * @since [产品/模块版本]
     */
    @ResponseBody
    @RequestMapping("/check/clearPaper/exec")
    public Result<?> clearPaper(@RequestBody Map<String, Object> criteria){
    	Result<?> result = new Result<String>();
    	String resultCode = SysParamsDict.STATUS_CODE.SUCCESS.getValue();
        try{
           this.coursePaperService.clearPaper(criteria);
        }catch(Exception e){
        	resultCode = SysParamsDict.STATUS_CODE.FAIL.getValue();
        }
        result.setResultCode(resultCode);
        return result;
    }
    
    /**
     * 科目答卷切割
        * @Title: doCropPaper
        * @param @return    参数
        * @return Result<?>    返回类型
        * @throws
     */
    @ResponseBody
    @RequestMapping("/crop/cropPaper/exec")
    public Result<?> doCropPaper(HttpServletRequest request){
    	Result<?> result = new Result<String>();
    	String resultCode = SysParamsDict.CHECK_STATUS_CODE.SUCCESS.getValue();
    	Map<String, Object> criteria = new HashMap<String, Object>();
    	String dotChar = ".";
		String fileFormat = Dict.IMAGE_FORMAT.PNG;
		
    	String batchId = getParaValue("batchId");
    	String gradeNo = getParaValue("gradeNo");
    	String courseNo = getParaValue("courseNo");
    	criteria.put("gradeNo", gradeNo);
        criteria.put("courseNo", courseNo);
        criteria.put("batchId", batchId);
        
        request.getSession().removeAttribute("djzs2");
        request.getSession().removeAttribute("clzs2");
        request.getSession().removeAttribute("djcut_count");
        request.getSession().removeAttribute("djcut_retCode");
        request.getSession().removeAttribute("djcut_succCount");
        request.getSession().removeAttribute("djcut_failCount");
        Map<String,CourseTemplate> mbMap = new HashMap<String,CourseTemplate>();
        Map<String,List<CourseTemplateArea>> areaListMap = new HashMap<String,List<CourseTemplateArea>>();
        List<String> tempIds = new ArrayList<String>();
        String cropDir = MessageUtil.getExtConfig("fj.course.paper.crop.url");
        String paperDir = MessageUtil.getExtConfig("fj.course.paper.url");
        
    	try{
    		//查询模板记录
            List<CourseTemplate> mbList = this.courseTemplateService.listEntities(criteria);
            if(mbList.size()>0){
                for(CourseTemplate record : mbList){
                    mbMap.put(record.getId(), record);
                    tempIds.add(record.getId());
                }
            }
            
            //查询所有模板对应的截图区域
            if(!mbMap.isEmpty()){
            	Map<String, Object> criteria_ = new HashMap<String, Object>();
            	criteria_.put("tempIds", tempIds);
            	String[] lxArr = {"3","4","5"};
            	criteria_.put("lxList", Arrays.asList(lxArr));
                List<CourseTemplateArea> areaList_ = this.courseTemplateService.getCourseTemplateAreaList(criteria_);
                if(areaList_.size()>0){
                    for(CourseTemplateArea record : areaList_){
                        String fjid = record.getOwner();//附件id
                        if(areaListMap==null){
                        	areaListMap = new HashMap<String,List<CourseTemplateArea>>();
                            List<CourseTemplateArea> list= new ArrayList<CourseTemplateArea>();
                            list.add(record);
                            areaListMap.put(fjid, list);
                        }else{
                            if(areaListMap.get(fjid) != null){
                                List<CourseTemplateArea> list = areaListMap.get(fjid);
                                list.add(record);
                                areaListMap.put(fjid, list);
                            }else{
                                List<CourseTemplateArea> list = new ArrayList<CourseTemplateArea>();
                                list.add(record);
                                areaListMap.put(fjid, list);
                            }
                        }
                    }
                }
            }
            
            int count=0;
            int succCount=0;//记录成功数
            int failCount=0;//记录失败数
            //查询需要裁剪的答卷
            if(!CollectionUtils.isEmpty(tempIds)){
            	 String relativePath = "kmdj_crop/"+batchId+"_"+courseNo+"/";//截图后图片存放相对目录
                 String rootDirUrl = cropDir + relativePath;//截图后图片存放实际目录
                 //创建图片裁剪存放目录
                 FileUtil.createDir(rootDirUrl);
                 
            	//删除考号重复的答卷
            	criteria.put("tempIds", tempIds);
                this.coursePaperService.deleteKsbhExists(criteria);
                
                Integer[] passArr = {1,2};
                criteria.put("isPassList", Arrays.asList(passArr));
                criteria.put("cropStatus", false);
                List<CoursePaperDetail> paperList = this.coursePaperService.findCoursePaperDetailList(criteria);
                count = paperList.size();
                int clzs=0;//处理总数
                if(count > 0){
                	request.getSession().setAttribute("djzs2", count);
                	for(CoursePaperDetail record : paperList){
                		String djid = record.getId();//答卷id
                        String owner = record.getOwner();//科目模板id
                        String studentNo = record.getStudentNo();//考生编号
                        String sourceUrl = paperDir + record.getFilePath();//答卷存储路径
                        if(areaListMap.get(owner)!=null){
                        	//获取模板对应的截取范围
                            List<CourseTemplateArea> areaList = areaListMap.get(owner);
                            int areaSzie = areaList.size();//截图总数
                            int cgs = 0;
                            boolean flag_ =false;
                            for(CourseTemplateArea r : areaList){
                                String areaId = r.getId();//裁剪区域id
                                String imgName = UUIDUtils.UUID() + dotChar + fileFormat;
                                Integer type = Integer.valueOf(r.getLx());
                                int x1 = Integer.valueOf(r.getX1());
                                int x2 = Integer.valueOf(r.getX2());
                                int y1 = Integer.valueOf(r.getY1());
                                int y2 = Integer.valueOf(r.getY2());
                                int width = x2 - x1;
                                int height = y2 - y1;
                                //原图裁剪
                                try{
                                	Map<String,Object> params = new HashMap<String,Object>();
                                	params.put("sourceUrl", sourceUrl);
        	                        params.put("destUrl", rootDirUrl+imgName);
        	                        params.put("start_x", x1);
        	                        params.put("start_y", y1);
        	                        params.put("width", width);
        	                        params.put("height", height);
        	                        this.cropService.imageCropFromUrl(params);
                                    //cropService.imageCropFromUrl(width, height, x1, y1, sourceUrl, rootDirUrl+imgName);
                                    //将裁剪后的图片信息保存到数据表中
        	                        CoursePaperCrop entity = new CoursePaperCrop();
        	                        entity.setStudentNo(studentNo);
        	                        entity.setAreaId(areaId);
        	                        entity.setOwner(djid);
        	                        entity.setFilePath(relativePath + imgName);
        	                        entity.setStatus(0);
        	                        entity.setWidth(width);
        	                        entity.setHeight(height);
        	                        entity.setType(type);
        	                        this.coursePaperService.insertCoursePaperCrop(entity);
                                    cgs++;
                                    flag_ = true;
                                }catch(Exception e){
                                	resultCode = SysParamsDict.CHECK_STATUS_CODE.FAIL.getValue();
                                    System.out.println(sourceUrl+"图片中裁剪位置("+x1+","+y1+"),("+x2+","+y2+")出错！~~~~~~~~~~~~~~~~~~~~");
                                }
                            }
                            //更新答卷表是否裁剪状态
                            if(flag_){
                            	CoursePaperDetail detail = new CoursePaperDetail();
                            	detail.setIsCrop(1);
                            	detail.setId(djid);
                            	this.coursePaperService.updatePaperDetailStatus(detail);
                            }
                            
                            //统计答卷切割成功记录数
                            if(cgs==areaSzie){
                                succCount++;
                            }else{
                                failCount++;
                            }
                        }
                        
                        clzs++;
                        setSessionAttr("clzs2",clzs);
                	}
                }
                
                setSessionAttr("djcut_retCode", resultCode);
            }else{
            	setSessionAttr("djcut_retCode", resultCode);
            }
            
            setSessionAttr("djcut_count", count);
            setSessionAttr("djcut_succCount",succCount);
            setSessionAttr("djcut_failCount",failCount);
        }catch(Exception e){
        	resultCode = SysParamsDict.CHECK_STATUS_CODE.FAIL.getValue();
        }
        result.setResultCode(resultCode);
        return result;
    }
    
    /**
     * 获取图片裁剪进度session参数
        * @Title: getPaperCropSession
        * @param @param request
        * @param @return    参数
        * @return Result<?>    返回类型
        * @throws
     */
    @ResponseBody
    @RequestMapping("/crop/getPaperCropSession")
    public Result<?> getPaperCropSession(@RequestBody Map<String, Object> criteria){
    	Result<?> result = new Result<String>();
    	Map<String,Object> resultMap = new HashMap<String,Object>();
    	int djzs = getSessionAttr("djzs2")==null?0:Integer.parseInt(getSessionAttr("djzs2")+"");
        int clzs = getSessionAttr("clzs2")==null?0:Integer.parseInt(getSessionAttr("clzs2")+"");
        int bl =0;
        if(djzs>0){
            bl = (int)((clzs / Double.parseDouble(djzs+"")) * 100);
        }
        resultMap.put("djzs2",djzs);
        resultMap.put("clzs2",clzs);
        resultMap.put("bl2",bl);
        resultMap.put("count",getSessionAttr("djcut_count"));
        resultMap.put("succCount",getSessionAttr("djcut_succCount"));
        resultMap.put("failCount",getSessionAttr("djcut_failCount"));
        result.setData(resultMap);
        result.setResultCode((String) getSessionAttr("djcut_retCode"));
        return result;
    }
    
    /**
     * 跳转到答卷考号校正列表页面
        * @Title: paperCorrection
        * @param @param mv
        * @param @return    参数
        * @return ModelAndView    返回类型
        * @throws
     */
    @SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping("/paperCorrectionUI")
    public ModelAndView paperCorrectionUI(ModelAndView mv){
    	mv.setViewName(Views.CORR_LIST_VIEW);
    	String paperDir = MessageUtil.getExtConfig("fj.course.paper.url");
    	Map<String, Object> criteria = new HashMap<String, Object>();
    	String batchId = getParaValue("batchId");
    	String gradeNo = getParaValue("gradeNo");
    	String courseNo = getParaValue("courseNo");
		criteria.put("batchId", batchId);
		criteria.put("gradeNo", gradeNo);
		criteria.put("courseNo", courseNo);
		criteria.put("userId", Common.findUserSessionId());
		//查询正面模板设置数据
		criteria.put("zfmType", 1);
		criteria.put("existsCondition", true);
		String[] lxArr = {"1","9"};
    	criteria.put("lxList", Arrays.asList(lxArr));
    	Map<String,CourseTemplateArea> mbMap = this.courseTemplateService.getTemplateAreaMap(criteria);
        
        //查询答卷校验失败的记录，只查询正面数据
        criteria.put("isPass", 2);
        Pagination page = (Pagination) getRequestAttr("pagination");
        page.setPageSize(Pagination.PAGESIZE1);
        if(getParaValue("current") !=null){
        	page.setCurrent(Integer.parseInt(getParaValue("current")));
        }
        Pagination pagination = this.coursePaperService.findCoursePaperDetailPage(criteria, page);
		mv.addObject(Keys.KEY_PAGINATION, pagination);
		
		int multiple=0;
		List<CoursePaperDetail> list = (List<CoursePaperDetail>) pagination.getDatas();
        if(!CollectionUtils.isEmpty(list)){
        	Map<String,Object> criteria_ = new HashMap<String,Object>();
        	CoursePaperDetail record = list.get(0);
            int sffsetX = record.getOffsetX()==null ? 0 : record.getOffsetX();
            int offsetY = record.getOffsetY()==null ? 0 : record.getOffsetY();
            String sourceUrl = paperDir + record.getFilePath();//答卷存储路径
            //获取考号区域裁剪位置，将图片裁剪页面显示
            criteria_.put("record", mbMap.get("kh"));
            criteria_.put("sourceUrl", sourceUrl);
            criteria_.put("offsetX", sffsetX);
            criteria_.put("offsetY", offsetY);
            criteria_.put("lx", 1);
            Map<String,Object> map1 = cropService.getPositionBufferedImage(criteria_);
            multiple = Integer.parseInt(map1.get("width")+"")/800;//倍数
            
            //获取缺考区域裁剪位置，将图片裁剪页面显示
            criteria_.put("record", mbMap.get("qk"));
            criteria_.put("lx", 9);
            Map<String,Object> map2 = cropService.getPositionBufferedImage(criteria_);
            
            mv.addObject("imgUrlKh",map1.get("imgUrl"));
            mv.addObject("imgUrlQk",map2.get("imgUrl"));
            mv.addObject("fileName",record.getFileName().split("_")[0]);
            mv.addObject("id", record.getId());
        }
        
        Long pageNumber = (long) pagination.getCurrent();//页码
        Long totalPage = (long) pagination.getTotalPages();//总页数
        mv.addObject("current" , pageNumber);
        mv.addObject("totalPage" , totalPage);
        mv.addObject("nextPage" , pageNumber==totalPage ? pageNumber : pageNumber+1);
        mv.addObject("previousPage" , pageNumber==1 ? pageNumber : pageNumber-1);
        mv.addObject("multiple",multiple);
		mv.addObject("batchId", batchId);
		mv.addObject("gradeNo", gradeNo);
		mv.addObject("courseNo", courseNo);
    	return mv;
    }
    
    /**
     * @throws IOException 
     * 保存答卷考生编号信息
        * @Title: doSavePaperStudent
        * @param @return    参数
        * @return Result<?>    返回类型
        * @throws
     */
    @ResponseBody
    @RequestMapping("/savePaperStudent/exec")
    public Result<?> doSavePaperStudent(@RequestBody Map<String,Object> criteria) throws IOException{
    	Result<?> result = new Result<String>();
    	Map<String,Map<String,Integer>> kmdjDiffAll = new HashMap<String,Map<String,Integer>>();//存放答卷记录的偏差值信息
        Map<String,Integer> diffMap = new HashMap<String,Integer>();//偏差map
        Map<String,Integer> diffMap2 = new HashMap<String,Integer>();//偏差map
        Map<String,String> ksxxMap = new HashMap<String,String>();//基本参数
        Map<String,Object> mbMap = new HashMap<String,Object>();//模板参数
        
        String resultCode = SysParamsDict.STATUS_CODE.SUCCESS.getValue();
        List<String> ids = new ArrayList<String>();
        String id = criteria.get("detailId")+"";//记录id
        ids.add(id);
        
        ksxxMap.put("batchId", criteria.get("batchId")+"");
        ksxxMap.put("gradeNo", criteria.get("gradeNo")+"");
        ksxxMap.put("courseNo", criteria.get("courseNo")+"");
        
        //根据文件名称查询反面答卷，并更新信息
        criteria.put("isPass", 2);
        criteria.put("zfmType", 2);
        CoursePaperDetail detail2 = this.coursePaperService.findCoursePaperDetailEntity(criteria);
        String fmid = "";
        if(detail2 != null){
        	fmid = detail2.getId();
        	ids.add(fmid);
        	mbMap.put("backId", detail2.getCourseTemplateId());
        	int p_x = detail2.getOffsetX()==null?0:detail2.getOffsetX();
            int p_y = detail2.getOffsetY()==null?0:detail2.getOffsetY();
            diffMap2.put("p_x", p_x);
            diffMap2.put("p_y", p_y);
            kmdjDiffAll.put(fmid, diffMap2);
        }
        
        //删除已有记录之外的重复数据
        criteria.put("ids", ids);
        this.coursePaperService.deleteCoursePaperForRepeat(criteria);
        try{
        	//查询答卷正面数据
        	Map<String,Object> criteria_ = new HashMap<String,Object>();
        	criteria_.put("id", id);
            CoursePaperDetail detail = this.coursePaperService.findCoursePaperDetailEntity(criteria_);
            if(detail != null){
            	mbMap.put("frontId", detail.getCourseTemplateId());//正面模板id
                //double rotate = detail.getRotate()==null?0d:Double.parseDouble(detail.getRotate());//偏正角度
                //String sourceUrl = configProp.getValue("fj.course.paper.url") + detail.getFilePath();//正面答卷存储路径
                Map<String,Object> args = new HashMap<String,Object>();
                args.put("rotate", detail.getRotate()==null?0d:Double.parseDouble(detail.getRotate()));//偏正角度
                args.put("sourceUrl", MessageUtil.getExtConfig("fj.course.paper.url") + detail.getFilePath());//正面答卷存储路径
                
                //放置所需参数map
                Map<String,Map<String,CourseTemplateArea>> cjcsMap = this.courseTemplateService.getTemplateParams(mbMap);//查询答卷模板数据
                int p_x = detail.getOffsetX()==null?0:detail.getOffsetX();
                int p_y = detail.getOffsetY()==null?0:detail.getOffsetY();
                diffMap.put("p_x", p_x);
                diffMap.put("p_y", p_y);
                kmdjDiffAll.put(id, diffMap);
                
                Map<String,Object> param = new HashMap<String,Object>();
            	param.put("record",detail);
            	param.put("image",  this.cropService.imageRotateToBuff(args));//执行偏正校正
            	param.put("kmdjDiffAll",kmdjDiffAll);
            	param.put("cjcsMap",cjcsMap);
            	param.put("ksxxMap",ksxxMap);
            	param.put("studentNo",criteria.get("studentNo"));
                this.cropService.cropImageForZm(param);//裁剪图片-正面
                if(mbMap.containsKey("backId")){
                	param.put("record",detail2);
                	param.put("kmdjDiffAll",kmdjDiffAll);
                	this.cropService.cropImageForFm(param);//裁剪图片-反面
                }
                
                //更新答卷校验及裁剪状态
                detail = new CoursePaperDetail();
                detail.setId(id);
                detail.setStudentNo(criteria.get("studentNo")+"");
                detail.setIsCrop(1);
                detail.setIsPass(Integer.valueOf(criteria.get("sfqk")+""));
                this.coursePaperService.updatePaperDetailStatus(detail);//更新正面答卷信息
                if(mbMap.containsKey("backId")){
                	detail.setId(fmid);
                	this.coursePaperService.updatePaperDetailStatus(detail);//更新反面答卷信息
                }
            }
        }catch(ServiceException e){
        	resultCode = e.getErrorNo();
        }
        
        result.setResultCode(resultCode);
    	return result;
    }
    
    /**
     * 查询已上传的考生答卷列表页面
        * @Title: paperAlreadyUploadUI
        * @param @param mv
        * @param @return    参数
        * @return ModelAndView    返回类型
        * @throws
     */
    @ResponseBody
    @RequestMapping("/papers/paperAlreadyUploadUI")
    public ModelAndView paperAlreadyUploadUI(ModelAndView mv){
    	mv.setViewName(Views.PAPER_UPLOAD_LIST_VIEW);
    	Map<String, Object> criteria = new HashMap<String, Object>();
    	String batchId = getParaValue("batchId");
    	String gradeNo = getParaValue("gradeNo");
    	String courseNo = getParaValue("courseNo");
		criteria.put("batchId", batchId);
		criteria.put("gradeNo", gradeNo);
		criteria.put("courseNo", courseNo);
		//criteria.put("userId", Common.findUserSessionId());
		String query_sftg = getParaValue("query_sftg");
		String query_sfcj = getParaValue("query_sfcj");
		String query_zfm = getParaValue("query_zfm");
		String query_kh = getParaValue("query_kh");
		String query_wjmc = getParaValue("query_wjmc");
		criteria.put("existsCondition", true);
		if(!StringUtils.isEmpty(query_sfcj)){
			criteria.put("isCrop", query_sfcj);
		}
		if(!StringUtils.isEmpty(query_sftg)){
			criteria.put("isPass", query_sftg);
		}
		if(!StringUtils.isEmpty(query_zfm)){
			criteria.put("zfmType", query_zfm);
		}
		criteria.put("studentNoLike", query_kh);
		criteria.put("fileNameLike", query_wjmc);
		criteria.put("isMap", true);
		Pagination page = (Pagination) getRequestAttr("pagination");
		Pagination pagination = this.coursePaperService.findCoursePaperDetailPage(criteria, page);
		mv.addObject(Keys.KEY_PAGINATION, pagination);
		mv.addObject("batchId", batchId);
		mv.addObject("gradeNo", gradeNo);
		mv.addObject("courseNo", courseNo);
		mv.addObject("query_sftg",query_sftg);
		mv.addObject("query_sfcj",query_sfcj);
		mv.addObject("query_zfm",query_zfm);
		mv.addObject("query_kh",query_kh);
		mv.addObject("query_wjmc",query_wjmc);
    	return mv;
    }
    
    /**
     * 删除科目答卷
        * @Title: doDeletePaper
        * @param @param criteria
        * @param @return    参数
        * @return Result<?>    返回类型
        * @throws
     */
    @ResponseBody
    @RequestMapping("/papers/deletePaper/exec")
    public Result<?> doDeletePaper(@RequestBody Map<String,Object> criteria){
    	Result<?> result = new Result<String>();
    	try{
    		String[] ids = String.valueOf(criteria.get("ids")).split(";");
    		criteria.put("ids", Arrays.asList(ids));
    		this.coursePaperService.clearPaper(criteria);
    		result.setResultCode(SysParamsDict.STATUS_CODE.SUCCESS.getValue());
    	}catch(ServiceException e){
    		result.setResultCode(e.getErrorNo());
    	}
    	return result;
    }
    
    /**
     * 清空答卷删除临时文件缓存
        * @Title: doClearCached
        * @param @param criteria
        * @param @return    参数
        * @return Result<?>    返回类型
        * @throws
     */
    @ResponseBody
    @RequestMapping("/papers/clearCached/exec")
    public Result<?> doClearCached(@RequestBody Map<String,Object> criteria){
    	Result<?> result = new Result<String>();
    	String paperDir = MessageUtil.getExtConfig("fj.course.paper.convent.url");
    	try{
    		if(Integer.valueOf(criteria.get("type")+"")==0){
    			this.coursePaperService.clearPaper(criteria);
    		}
            FileUtil.deleteDir(paperDir);//删除转换答卷目录
            result.setResultCode(SysParamsDict.STATUS_CODE.SUCCESS.getValue());
    	}catch(ServiceException e){
    		result.setResultCode(e.getErrorNo());
    	}
    	return result;
    }
    
    @RequestMapping("/papers/detailUI")
    public ModelAndView detailUI(ModelAndView mv){
    	mv.setViewName(Views.PAPER_DETAIL_VIEW);
    	String paperDir = MessageUtil.getExtConfig("fj.course.paper.url");
    	String conventDir = MessageUtil.getExtConfig("fj.course.paper.convent.url");
    	FileUtil.createDir(conventDir);
    	
    	Map<String, Object> criteria = new HashMap<String, Object>();
    	criteria.put("id", getParaValue("courseTemplateId"));
    	CourseTemplate temp = this.courseTemplateService.findEntity(criteria);
    	int screen_width = Integer.parseInt(getParaValue("screen_width"));//屏幕宽度
    	String sfsf ="false";//缩放缩放图像 false-不缩放  true-缩放
    	Integer img_width = temp.getImgWidth();
        Integer img_height = temp.getImgHeight();
        float width_bl = 1f;
        if(img_width > screen_width){
        	//图片宽度大于1500PX，将图像缩放一半尺寸显示
        	width_bl = Float.valueOf(screen_width) / img_width;
            img_width = (int) (img_width * width_bl);
            img_height = (int) (img_height * width_bl);
            sfsf = "true";
        }
        
        //查询答卷
        criteria.put("id",getParaValue("id"));
        CoursePaperDetail detail = this.coursePaperService.findCoursePaperDetailEntity(criteria);
        String imgName = UUIDUtils.UUID() + Dict.SEPARATOR.DOT + Dict.IMAGE_FORMAT.PNG;
        if(detail != null){
            try {
            	//转换图片格式为PNG，用于页面显示
            	criteria.put("sourceUrl", paperDir + detail.getFilePath());//源路径
            	criteria.put("destUrl", conventDir + imgName);//目标路径
            	criteria.put("rotate", 0.0d);
            	criteria.put("quality", 0.6f);
                this.cropService.imageRotateToFile(criteria);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mv.addObject("imgWidth", img_width);
        mv.addObject("imgHeight", img_height);
        mv.addObject("sourceUrl", imgName);
        mv.addObject("sfsf", sfsf);
    	return mv;
    }
    
    /**
     * 查询答卷未入系统考生页面
        * @Title: paperSurplusStudentUI
        * @param @param mv
        * @param @return    参数
        * @return ModelAndView    返回类型
        * @throws
     */
    @RequestMapping("/paperSurplusStudentUI")
    public ModelAndView paperSurplusStudentUI(ModelAndView mv){
    	mv.setViewName(Views.PAPER_SURPLUS_STUDENT_VIEW);
    	Map<String, Object> criteria = new HashMap<String, Object>();
    	criteria.put("userId", Common.findUserSessionId());
    	String batchId = getParaValue("batchId");
    	String gradeNo = getParaValue("gradeNo");
    	String courseNo = getParaValue("courseNo");
		criteria.put("batchId", batchId);
		criteria.put("gradeNo", gradeNo);
		criteria.put("courseNo", courseNo);
		String examNo = getParaValue("khxm");
        if(StringUtils.isNotEmpty(examNo)){
            criteria.put("examNo", examNo);
        }
        String classNo = getParaValue("classNo");
        if(StringUtils.isNotEmpty(classNo)){
            criteria.put("classNo",classNo);
        }
        Pagination page = (Pagination) getRequestAttr("pagination");
		Pagination pagination = this.coursePaperService.findCoursePaperSurplusStudentPage(criteria, page);
		mv.addObject(Keys.KEY_PAGINATION, pagination);
		mv.addObject("batchId", batchId);
		mv.addObject("gradeNo", gradeNo);
		mv.addObject("courseNo", courseNo);
		mv.addObject("khxm", examNo);
		mv.addObject("classNo", classNo);
		mv.addObject("classs", this.coursePaperService.querySurplusStudentClass(criteria));
    	return mv;
    }
    
	class Views {
		/**
		 * index视图
		 */
		public static final String LIST_INDEX = "/manage/examPaper/list";
		
		/**
		 * 列表视图
		 */
		public static final String LIST_VIEW = "/manage/examPaper/list";

		/**
		 * 上传视图
		 */
		public static final String UPLOAD_VIEW = "/manage/examPaper/upload";
		
		/**
		 * 考号校正视图
		 */
		public static final String CORR_LIST_VIEW = "/manage/examPaper/correction";
		
		/**
		 * 已上传考生答卷视图
		 */
		public static final String PAPER_UPLOAD_LIST_VIEW = "/manage/examPaper/papers";
		
		/**
		 * 具体答卷视图
		 */
		public static final String PAPER_DETAIL_VIEW = "/manage/examPaper/detail";
		
		/**
		 * 答卷未入系统考生视图
		 */
		public static final String PAPER_SURPLUS_STUDENT_VIEW = "/manage/examPaper/surplus_student";
	}
}
